package com.qall.configserver.util;

import com.qall.configserver.constant.Constant;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;

import java.io.*;

import java.util.ArrayList;
import java.util.HashMap;

import java.util.List;
import java.util.Map;

@Service
public class FileUtil {

    @Value("${file.root.path}")
    private String filePathPrefix;

    private static final String SUFFIX = ".properties";

    public void writeCommonConfigToFile(@NonNull String nameSpace, @Nullable Map<String, String> data) {
        String path = getFilePath(nameSpace, null);
        writeToFile(path, data);
    }

    public void writeNodeConfigToFile(String appId, String nameSpace, Map<String, String> data) {
        String path = getFilePath(nameSpace, appId);
        writeToFile(path, data);

    }

    public Map<String, String> getConfig(String nameSpace, String appId) {
        String path = getFilePath(nameSpace, appId);
        Map<String, String> map = com.qall.util.FileUtil.readFile(path);
        return map;
    }

    public String getFilePath(String nameSpace, String appId) {
        return filePathPrefix +
                (nameSpace == null ? "" : nameSpace)
                + (appId == null ? "" : "_" + appId)
                + SUFFIX;
    }


    /**
     * 写文件
     *
     * @param path
     * @param baseDataEntityList
     */
    private void writeToFile(String path, Map<String, String> baseDataEntityList) {
        synchronized (path.intern()) {
            File file = new File(path);
            try {
                FileWriter fr = new FileWriter(file);
                BufferedWriter bufferedWriter = new BufferedWriter(fr);
                for (Map.Entry<String, String> entity : baseDataEntityList.entrySet()) {
                    bufferedWriter.write(entity.getKey() + Constant.SPLIT + entity.getValue());
                    bufferedWriter.newLine();
                }
                bufferedWriter.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }



    /**
     * 获取所有配置文件
     *
     * @return
     */
    public List<String> getNameList() {
        List<String> list = new ArrayList<String>();
        File file = new File(filePathPrefix);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File child : files) {
                list.add(child.getName());
            }
        }
        return list;
    }

}
